<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller{
	public function __construct()
	{
		parent::__construct();
        $this->load->helper('captcha');
        $this->load->library('form_validation');
        $this->load->model('ghc_user_model');
        $this->load->model('ghc_blog_model');
        $this->load->model('ghc_sort_model');
        $this->load->model('ghc_options_model');
	}

	public function index()
	{
        if(!$this->is_Session())
        {//没有登录
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        else
        {//登录过了
            $data['username'] = $this->session->userdata('username');
            $data['allviews'] = $this->ghc_blog_model->getViewNums();
            $data['indexviews'] = $this->ghc_options_model->getIndexViews();
            $data['views'] = $this->ghc_blog_model->getAnyView();
            for($i=0;$i<count($data['views']);$i++)
            {
                $data['viewname'][$i] = $this->ghc_sort_model->getSortNameBySid($data['views'][$i]->sortid);
            }

            $data['blogs'] = $this->ghc_blog_model->getAnyBlog();
            for($i=0;$i<count($data['blogs']);$i++)
            {
                $data['sortname'][$i] = $this->ghc_sort_model->getSortNameBySid($data['views'][$i]->sortid);
            }
            //var_dump($data['views']);
            $this->load->view('admin/index',$data);
        }
	}


    /**
     *登录界面
     * 如果session存在 则跳转主页面
     */
    public function login()
	{
        $userid = $this->session->userdata('userid');
		if(!$userid)
		{//没有登录
            $this->load->view('admin/sign-in');

		}
		else
		{//登录过了
			header("location:".SITE_URL.'index.php/admin');
            exit;
		}
	}

    public function logout()
    {
        $userid = $this->session->userdata('userid');
        if(!$userid)
        {//没有登录
            $this->load->view('admin/sign-in');
            exit;
        }
        else
        {//登录过了
            $this->session->unset_userdata('userid');
            $this->session->unset_userdata('username');
            $this->session->unset_userdata('role');
            $this->session->sess_destroy();
            header("location:".SITE_URL.'index.php/admin');
            exit;
        }
    }

    /**
     *一个中间控制函数，用户提交信息到这里
     * 如果正确
     *      跳转后台首页
     * 否则
     *      继续login
     */
    public function logincheck()
	{
        //验证码验证
        $code = strtolower($this->session->userdata('code'));
        $getcode = strtolower($this->input->post('captcha'));
        if($code != $getcode)
        {
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $seepassword = $this->input->post('password');
        //设置验证规则
        $this->form_validation->set_rules('username','username','trim|required|xss_clean');
        $this->form_validation->set_rules('password','password','required|md5|xss_clean');
        if($this->form_validation->run()  == TRUE)
        {//通过表单验证
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            //进行数据库用户验证
            $uid = $this->ghc_user_model->isUser($username,$password);
            if(0 != $uid)
            {//存在用户  存储用户信息到session 用户uid 角色
                $this->session->set_userdata('userid',$uid);
                $this->session->set_userdata('role',$this->ghc_user_model->getUserByUid($uid)->role);
                $this->session->set_userdata('username',$username);
                //echo "session OK";
                header("location:".SITE_URL.'index.php/admin/');
                exit;
            }
            else{//不存在该用户
                //echo "user not find";
                $log = sprintf("attempt login, username:%s, password:%s, IP:%s, UserAgent:%s.",$username,$seepassword,$this->input->ip_address(),$this->input->user_agent());
                log_message('error', $log);
                header("location:".SITE_URL.'index.php/admin/login');
                exit;
            }

        }
        else
        {//input is not legal
            //echo "input is not legal";
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
	}

    public function accountinfo()
    {
        if(!$this->is_Session())
        {//没有登录
            header("location:".SITE_URL.'index.php/admin/login');
            exit;
        }
        $user = $this->ghc_user_model->getUserByUid($this->session->userdata('userid'));
        $data['lastlogindate'] = date('Y-m-d   h:i:sa',$user->lastlogindate);
        $data['loginerror'] = $user->loginerror;
        $data['logins'] = $user->logins;
        $data['username'] = $this->session->userdata('username');
        $this->load->view('admin/accountinfo',$data);
    }

    private function setuser()
    {
        //$username = "root";
        //$password = md5("root");
        //$this->ghc_user_model->insert($username,$password);
        $query = $this->ghc_user_model->getFirstUser();
        //var_dump($query);
        var_dump($query->first_row());
        $this->test();
    }

    /**
     * @return bool
     * 判断是否存在username 和 role(角色)
     */
    private function is_Session()
	{
        $userid = $this->session->userdata('userid');
		$value = $this->session->userdata('username');
        $role = $this->session->userdata('role');
		if($value && $role && $userid)
		{
			return TRUE;
		}
		else
		{
            $log = sprintf("no login visit,  IP:%s, UserAgent:%s.",$this->input->ip_address(),$this->input->user_agent());
            log_message('error', $log);
			return FALSE;
		}
	}

    /**
     *生成验证码
     */
    public function code()
    {
        #调用函数生成验证码
        $vals = array('word_length' => 4,);
        $code = create_captcha($vals);

        $this->session->set_userdata('code',$code);
    }
}